<template>
  <VsFormItem
    :label="label"
    required
  >
    <div class="base-option-color">
      <div class="list">
        <div
          v-for="(item, index) in themes"
          :key="item.key"
          class="item"
          @click="selectColor(item)"
        >
          <ColorTheme
            :config="config"
            :form="form"
            :component-style="item.componentStyle"
            :type="item.type"
            :theme-conf="item"
            :is-checked="isChecked(item)"
            :enum-prikey="enumPrikey"
            @del-theme="delTheme"
            @reset-theme="resetTheme"
          />
        </div>
        <div class="item">
          <ColorTheme
            :config="config"
            :form="form"
            action="new"
            :component-style="form.componentStyle"
            :type="type"
            @save-new-theme="saveNewTheme"
          />
        </div>
      </div>
    </div>
  </VsFormItem>
</template>
<script>
import { $demoi18n } from '@/utils/lang';
import { $confirm } from '@/utils/util';
import ColorTheme from '../color-theme/color-theme.vue';
import { nextTick } from 'vue';

export default {
  components: {
    ColorTheme,
  },
  props: {
    config: Object, // 组件的全部配置
    form: Object, // 对应具体组件的property
    colorGroup: Object, // 对应原来组件的颜色套餐
    label: {
      type: String,
      default: $demoi18n('word.color'),
    },
    colorThemesKey: {
      type: String,
      default: 'colorThemes',
    },
    colorKey: {
      type: String,
      default: 'color',
    },
    enumPrikey: String, // 自定义颜色主题下拉选择字段名
  },
  data() {
    return {
      xvueTheme: window._adoPremise.uc.theme, // 'dark',
      type: 'single', // single | gradient
    };
  },
  computed: {
    themes() {
      const themes = this.getThemes();
      return themes;
    },
  },
  watch: {
    'form.componentStyle'() {
      this.selectColor(this.themes[0]);
    },
  },
  created() {
    this.initColorType();
    this.initColorThemes();
  },
  methods: {
    initColorType() {
      // 分析原来的颜色主题是 single 还是 gradient
      if (this.colorGroup && this.colorGroup.dark) {
        const keys = Object.keys(this.colorGroup.dark);
        const key = keys[0];
        if (key) {
          const color = this.colorGroup.dark[key][0];
          if (Array.isArray(color)) {
            this.type = 'gradient';
          } else {
            this.type = 'single';
          }
        }
      }
    },
    getColorGroupThemes() {
      const { colorGroup } = this;
      const colorThemes = [];
      Object.entries(colorGroup).map(([i]) => {
        Object.entries(colorGroup[i]).map(([j]) => {
          const colors = colorGroup[i][j];
          colorThemes.push({
            type: Array.isArray(colors[0]) ? 'gradient' : 'single',
            componentStyle: i,
            key: j,
            colors: colors,
            colorType: Array.isArray(colors[0]) ? 'gradient' : 'single',
            colorContentSource: 'original',
            'single_original_content': [],
            'single_custom_content': [],
            'gradient_original_content': [],
            'gradient_custom_content': [],
          });
        });
      });
      return colorThemes;
    },

    // 兼容旧数据库已保存配置
    _fixThemes(themes) {
      themes.forEach(n => {
        n.colorType = n.colorType || n.type || 'single';
        n.colorContentSource = n.colorContentSource || 'original';
        n['single_original_content'] = n.single_original_content || [];
        n['single_custom_content'] = n.single_custom_content || [];
        n['gradient_original_content'] = n.gradient_original_content || [];
        n['gradient_custom_content'] = n.gradient_custom_content || [];
      });
      return themes;
    },

    getThemes(filter = true) {
      let themes = [];
      if (!this.form[this.colorThemesKey] || !this.form[this.colorThemesKey].length) {
        themes = this.getColorGroupThemes();
      } else {
        themes = this.form[this.colorThemesKey];
        themes = this._fixThemes(themes);
      }

      if (filter) {
        themes = themes.filter(n => n.componentStyle === this.form.componentStyle);
      }
      return themes;
    },
    initColorThemes() {
      const themes = this.getThemes(false);

      // 补充当前组件主题色
      const curColor = this.form[this.colorKey];
      if (typeof curColor === 'object') {
        const hasColor = themes.some(n => curColor.key === n.key && curColor.componentStyle === n.componentStyle);
        if (!hasColor) {
          themes.unshift(JSON.parse(JSON.stringify(curColor)));
        }
      }
      nextTick(() => {
        this.form[this.colorThemesKey] = themes;
      });
    },
    saveNewTheme(item) {
      this.form[this.colorThemesKey].push(item);
    },
    delTheme(item) {
      if (this.themes.length <= 1) {
        this.$message({
          message: this.$demoi18n('message.keepOneThemeColor'),
          type: 'warning',
          customClass: `vis_message_${this.xvueTheme}`,
        });
        return;
      }

      $confirm(this.$demoi18n('message.delThemeConfirm'), this.$demoi18n('popup.title.tips'), {
        confirmButtonText: this.$demoi18n('btn.confirm'),
        cancelButtonText: this.$demoi18n('btn.cancel'),
        type: 'warning',
      }).then(() => {
        // 自动选中下一个颜色
        this.autoSelectNextColor(item);

        this.form[this.colorThemesKey] = this.form[this.colorThemesKey].filter(n => {
          const flag = n.key !== item.key || n.componentStyle !== item.componentStyle;
          return flag;
        });
      });
    },
    resetTheme(item) {
      // 恢复原主题色
      const colorsOrigin = this.colorGroup[item.componentStyle][item.key];
      if (colorsOrigin) {
        item.colors = JSON.parse(JSON.stringify(colorsOrigin));
      }
    },
    getFormColorKeyVal() {
      const color = this.form[this.colorKey];
      if (typeof color === 'string') {
        return color;
      } else if (typeof color === 'object') {
        return color.key;
      } else {
        return null;
      }
    },
    getRadioClass(item) {
      const colorKeyVal = this.getFormColorKeyVal();
      return item.key === colorKeyVal ? 'color_checked' : '';
    },
    selectColor(item) {
      this.form[this.colorKey] = item;
    },

    // 删除主题后自动选中下一个颜色
    autoSelectNextColor(item) {
      const index = this.themes.indexOf(item);
      let nextItem;
      if (index === this.themes.length - 1) {
        nextItem = this.themes[index - 1];
      } else {
        nextItem = this.themes[index + 1];
      }
      this.form[this.colorKey] = nextItem;
    },
    isChecked(item) {
      let checked = false;
      const color = this.form[this.colorKey];
      if (typeof color === 'string') {
        if (item.key === color) {
          checked = true;
        }
      } else if (typeof color === 'object') {
        if (item.key === color.key) {
          checked = true;
        }
      } else {}
      return checked;
    },
  },
};
</script>
<style lang="less" scoped>
.el-form-item {
  background: transparent;
}
.base-option-color {
  height: max-content;
  .list {
    display: flex;
    line-height: normal;
    flex-wrap: wrap;
    .item {
      background: #fff;
    }
  }
}
</style>
<style lang="less">
.vis_message_dark {
  background-color: #071f30;
  border-color: #116584;
  .el-message-box__title {
    color: #fff;
    .el-message-box__headerbtn {
      color: #fff !important;
      .el-message-box__close {
        color: #fff !important;
      }
    }
  }
  .el-message-box__content {
    color: #fff;
  }
  .el-message-box__btns {
    .el-button--default {
      background-color: #064559;
      border-color: #064559;
      color: #fff;
    }

    .el-button--primary {
      background-color: #0eb4c2;
      border-color: #0eb4c2;
      color: #fff;
    }
  }
}
</style>
